#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from antdb.common.antdb_exec_sql import ExecAntDBSql
from common.const import CMDResult
from common.logger import Logger
from common.parse_parafile import get_env_variable
from common.util import check_user_utils

from common.util.exec_utils import check_path_valid

LOGGER = Logger().get_logger("antdb.log")


def get_version(pid, client_path, os_username, service_ip, port):
    LOGGER.info(f"Get antdb version2!pid: {pid}")
    if not check_user_utils.check_os_user(os_username):
        LOGGER.error(f"Get antdb version fail, os user {os_username} is invalid.")
        return False, "", ""
    if not check_path_valid(client_path, False):
        LOGGER.error(f"adb_ctl path[{client_path}] is invalid")
        return False, "", ""
    db_user = get_env_variable(f'application_auth_authKey_{pid}')
    db_pwd = get_env_variable(f'application_auth_authPwd_{pid}')
    if not db_user or not db_pwd:
        LOGGER.error(f"Get db user and db password failed.")
        return False, "", ""
    sql_cmd = "select adb_version();"
    antdb_sql = ExecAntDBSql(pid, client_path, service_ip, port)
    return_code, std_out, err = antdb_sql.exec_sql_cmd_resource(os_username, sql_cmd, db_user, db_pwd)
    if return_code != CMDResult.SUCCESS.value:
        LOGGER.error(f"Get antdb version error!pid: {pid}, error: {err}")
        return False, "", ""
    parsed_output = ExecAntDBSql.parse_html_result(std_out)
    if len(parsed_output) != 1:
        LOGGER.error(f"Invalid parsed output.")
        return False, "", ""
    version_info = parsed_output[0].get("adb_version", "")
    if not version_info:
        LOGGER.error(f"Get version info failed.")
        return False, "", ""
    items = version_info.split(" ")
    if len(items) < 4:
        LOGGER.error(f"Invalid version info.")
        return False, "", ""
    pg_version = items[1]
    antdb_version = items[3]
    LOGGER.info(f"Success get antdb version version: pg_version {pg_version}, "
                f"antdb_version {antdb_version}!pid: {pid}")
    return True, pg_version, antdb_version
